//
//  PayViewController.m
//  JiuLe
//
//  Created by SunChao on 16/10/12.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "MoneyPayViewController.h"
#import "WXApiRequestHandler.h"
#import "MallRequestManager.h"
#import "WXApiManager.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import "AppDelegate.h"
#import "OrderDetailViewController.h"
#import "Constant.h"
@interface MoneyPayViewController ()<UIAlertViewDelegate>
@end

@implementation MoneyPayViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.sureButton.layer.cornerRadius = 25;
    self.tableView.scrollEnabled = NO;
    self.zhifubaoButton.selected =YES;
    self.tableView.tableFooterView = [[UIView alloc]init];
    [self.zhifubaoButton setBackgroundImage:[UIImage imageNamed:@"enselect"] forState:UIControlStateNormal];
    [self.zhifubaoButton setBackgroundImage:[UIImage imageNamed:@"ok"] forState:UIControlStateSelected];
    [self.weChatButton setBackgroundImage:[UIImage imageNamed:@"enselect"] forState:UIControlStateNormal];
    [self.weChatButton setBackgroundImage:[UIImage imageNamed:@"ok"] forState:UIControlStateSelected];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(payMoneyAcount:) name:SubmitOrdersIsClicked object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(PushToOrderVC) name:pushToOrderVC object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(BillPay:) name:OrderPay object:nil];
}
-(void)dealloc
{
    [super dealloc];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:SubmitOrdersIsClicked object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:pushToOrderVC object:nil];
}
- (void)BillPay:(NSNotification *)text
{
    NSLog(@"text:%@",text.userInfo);
    AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    app.orderId = [text.userInfo objectForKey:@"orderid"];
    self.ordertype = [text.userInfo objectForKey:@"ordertype"];
    app.orderType =self.ordertype;
}
//支付成功后的跳转
- (void)PushToOrderVC
{
    OrderDetailViewController *orderDetail = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"OrderDetailViewController"];
    if ([self.flag isEqualToString:@"1"]) {//从商品页跳转
        orderDetail.strOrderid = self.orderId;
        orderDetail.flag = @"1";
        [self.navigationController pushViewController:orderDetail animated:YES];
   }
    if ([self.flag isEqualToString:@"2"]) {//从服务续费缴纳跳转
        
    }
    if ([self.flag isEqualToString:@"3"]) {
        
    }
    else
    {//从订单页跳转
        [[NSNotificationCenter defaultCenter]postNotificationName:reloadOrderDetailVC object:nil];
    }
}
- (void)payMoneyAcount:(NSNotification *)text
{
    if ([[text.userInfo objectForKey:@"type"]isEqualToString:@"1"]) {
        NSDictionary *detail = [text.userInfo objectForKey:@"details"];
        self.orderId = [NSString stringWithFormat:@"%@",[detail objectForKey:@"orderid"]];
        if ([[text.userInfo objectForKey:@"ispay"]isEqualToString:@"0"]) {
            //积分支付  不需要调用第三方支付
            return;
        }else
        {
            self.orderId = [text.userInfo objectForKey:@"orderid"];
            self.ordertype = [text.userInfo objectForKey:@"type"];
            self.moneyLabel.text = [NSString stringWithFormat:@"￥%@",[detail objectForKey:@"payamount"]];
        }
    }
    if ([[text.userInfo objectForKey:@"type"]isEqualToString:@"2"]) {
        //服务费缴纳
        NSDictionary *detail = [text.userInfo objectForKey:@"details"];
        self.orderId = [NSString stringWithFormat:@"%@",[detail objectForKey:@"orderid"]];
        self.ordertype = [text.userInfo objectForKey:@"type"];
        self.moneyLabel.text = [NSString stringWithFormat:@"￥%@",[detail objectForKey:@"payamount"]];
    }
    AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    app.orderId = self.orderId;
    app.orderType =self.ordertype;
    [self.tableView reloadData];
    
}
#pragma mark - Table view data source
- (IBAction)weChatBtnClicked:(UIButton *)sender{
    NSLog(@"微信支付");
    if (sender.selected ==YES) {
        if (self.zhifubaoButton.selected == NO) {
            sender.selected =YES;
        }
        else
        {
             sender.selected =NO;
        }
       
    }else if (sender.selected ==NO){
        sender.selected =YES;
        self.zhifubaoButton.selected =NO;
    }
}
- (IBAction)zhifubaoBtnClicked:(UIButton *)sender {
    NSLog(@"支付宝支付");
    if (sender.selected ==YES) {
        if (self.weChatButton.selected ==NO) {
            sender.selected =YES;
        }else
        {
            sender.selected = NO;
        }
    }else if (sender.selected ==NO){
        sender.selected =YES;
        self.weChatButton.selected =NO;
    }
}
- (IBAction)sureBtnClicked:(UIButton *)sender {
   
    if ([self.flag isEqualToString:@"2"]) {
        //通知服务费缴纳移除支付页面
        [[NSNotificationCenter defaultCenter]postNotificationName:removeMoneyPayVCFromType2 object:nil];
    }else if ([self.flag isEqualToString:@"1"])
    {
        //通知商城页移除支付页面
        [[NSNotificationCenter defaultCenter]postNotificationName:removeMoneyPayVCFromType1 object:nil];

    }
    if ((self.zhifubaoButton.selected ==YES)) {
        [self payWithAlipayPay];
    }else if ((self.weChatButton.selected ==YES))
    {
        if (![WXApi isWXAppInstalled]) {
            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"没有安装微信" message:nil  delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alter show];
            return ;
        }else if (![WXApi isWXAppSupportApi])
        {
            NSLog(@"不支持微信支付");
            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"不支持微信支付" message:nil  delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alter show];
            return ;
        }
        NSLog(@"安装了微信,而且微信支持支付");
        NSLog(@"跳转微信");
        //  发起支付
        [self bizPay];
    }
    
}
- (void)bizPay
{
    [WXApiRequestHandler jumpToBizPayWithOrderId:self.orderId andOrderType:self.ordertype];
}

#pragma mark -UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == alertView.cancelButtonIndex)
        return;
    
    if (alertView.tag == kRecvGetMessageReqAlertTag) {
        
    }
}


#pragma mark   ==============点击订单支付行为==============
- (void)payWithAlipayPay
{
    NSURL * myURL_APP_A = [NSURL URLWithString:@"alipay:"];
    if (![[UIApplication sharedApplication] canOpenURL:myURL_APP_A]) {
        //如果没有安装支付宝客户端那么需要安装
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"没有安装支付宝钱包" message:nil  delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alter show];
        return;
    }
     NSString *appScheme = @"a2016101802218418";
    NSMutableDictionary *params = [NSMutableDictionary new];
    
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    [params setValue:userId forKey:@"user_id"];
    [params setValue:token forKey:@"token"];
    [params setObject:self.orderId forKey:@"orderid"];
    [params setObject:@"1" forKey:@"pay_type"];//1 支付宝 2 微信
    [params setObject:self.ordertype forKey:@"order_type"];
    [MallRequestManager post:Payrequest RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        NSDictionary *dict =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if (dict != nil) {
            NSDictionary *dict1 = [dict objectForKey:@"result"];
            NSDictionary *encrystring = [dict1 objectForKey:@"encrystring"];
            NSString *sign = [encrystring objectForKey:@"sign"];
            [[AlipaySDK defaultService] payOrder:sign fromScheme:appScheme callback:^(NSDictionary *resultDic)
            {
                NSLog(@"reslut = %@",resultDic);
                NSLog(@"memo: = %@",[resultDic objectForKey:@"memo"]);
            }];
        }
    }];

}
@end
